from flask import request
from .. import db
from app.main.model import User

class Employee(object):

    def listAll(self):
        users = User.query.filter().all()
        return users

    def create(self):
        payload = request.get_json()
        if payload == None:
            return {
                'desc': 'No payload is provided to create employee.',
                'code': 400
            }

        # Check for duplication
        userSave = User(payload)
        userSave.save()

        return {
            'desc': '成功',
            'code': 201
        }

    def update(self, empId):
        payload = request.get_json()
        if payload == None:
            return {
                'desc': 'No payload is provided to update employee.',
                'code': 400
            }
        try:
            empIds = User.query.filter(User.USER_ID==empId).first()
            
            empIds.USERNAME=payload['USERNAME']
            empIds.CREATED_BY=payload['CREATED_BY']
            empIds.CREATED_DATE=payload['CREATED_DATE']
            db.session.commit()
            
            return {'desc': "成功", 'code': 200}
        except:
            return {
                'desc': 'ID为 %s 的数据不存在.' % empId,
                'code': 400
            }

    def delete(self, empId):
        try:
            empIds = User.query.filter(User.USER_ID==empId).first()
            db.session.delete(empIds)
            db.session.commit()  
            return {'desc': "成功", 'code': 200}
        except:
            return {
                'desc': 'ID为 %s 的数据不存在.' % empId,
                'code': 400
                }    